
package com.onlineclass.dao;

import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.onlineclass.bean.Cart;
import com.onlineclass.util.JDBCUtils;


public class CartDAO {
	QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

	/**
	 * 加到购物车,返回1加车成功;返回0代表课程已存在
	 * @param courseId
	 * @param userId
	 */
	public long save(Integer courseId, Integer userId) {
		long nums = 0;
		try {
			//先查询购物车是否有该数据
			nums = qr.query("select count(1) from t_cart where courseId=? and userId=?", new ScalarHandler<Long>(), courseId, userId);
			if(nums>0) return 0;
			nums = qr.update("insert into t_cart(courseId,userId,created) values(?,?,now())", courseId, userId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return nums;
	}
	
	/**
	 * 根据用户id查询购物车所有课程信息
	 * @param userId
	 * @return
	 */
	public List<Cart> list(Integer userId) {
		List<Cart> list = null;

		try {
			list = qr.query(
					"select c.id,c.title,c.img,c.price,cart.id cartId from t_cart cart,t_course c where c.id=cart.courseId and cart.userId=?",
					new BeanListHandler<Cart>(Cart.class),userId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
}
